<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>知识付费管理系统</h2>
        <p>欢迎登录管理后台</p>
      </div>
      
      <el-form 
        ref="loginFormRef"
        :model="loginForm" 
        :rules="loginRules" 
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="account">
          <el-input
            v-model="loginForm.account"
            :placeholder="loginForm.userType === 'admin' ? '请输入管理员账号' : '请输入用户账号'"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-radio-group v-model="loginForm.userType" class="user-type-group">
            <el-radio :label="'user'">普通用户</el-radio>
            <el-radio :label="'admin'">管理员</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            class="login-button"
            :loading="loading"
            @click="handleLogin"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-footer">
        <p>© 2024 知识付费管理系统. All rights reserved.</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { loginApi } from '@/api/login'

const router = useRouter()
const loginFormRef = ref()
const loading = ref(false)

// 登录表单
const loginForm = reactive({
  account: '',
  password: '',
  userType: 'admin'
})

// 表单验证规则
const loginRules = {
  account: [
    { 
      required: true, 
      message: () => loginForm.userType === 'admin' ? '请输入管理员账号' : '请输入用户账号', 
      trigger: 'blur' 
    },
    { min: 2, max: 10, message: '账号长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 处理登录
const handleLogin = async () => {
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    // 调试信息
    console.log('登录表单数据:', loginForm)
    console.log('用户类型:', loginForm.userType)
    
    const response = await (loginForm.userType === 'admin' 
      ? loginApi.adminLogin(loginForm) 
      : loginApi.userLogin(loginForm)
    )
    
    console.log('登录响应:', response)
    console.log('响应类型:', typeof response)
    console.log('响应代码:', response.code)
    console.log('响应数据:', response.data)
    console.log('数据类型:', typeof response.data)
    
    if (response.code === 200) {
      // 检查具体的登录结果
      if (loginForm.userType === 'admin') {
        // 管理员登录 - 后端直接返回JWT token字符串
        console.log('管理员登录检查 - data:', response.data)
        console.log('管理员登录检查 - data类型:', typeof response.data)
        
        if (response.data && typeof response.data === 'string') {
          // 管理员登录成功，data就是JWT token
          ElMessage.success('登录成功')
          // 保存token
          localStorage.setItem('token', response.data)
          localStorage.setItem('userType', 'admin')
          localStorage.setItem('isLoggedIn', 'true')
          // 跳转到首页
          router.push('/dashboard')
        } else {
          console.log('管理员登录失败 - data不是字符串:', response.data)
          ElMessage.error('登录失败')
        }
      } else {
        // 普通用户登录，检查data.msg
        console.log('用户登录检查 - data.msg:', response.data?.msg)
        if (response.data && response.data.msg === "登录成功") {
          ElMessage.success('登录成功')
          // 保存用户信息
          localStorage.setItem('userInfo', JSON.stringify(response.data.user))
          localStorage.setItem('userType', 'user')
          localStorage.setItem('isLoggedIn', 'true')
          // 给普通用户设置一个标识token（或者设为空，但不影响路由守卫的判断逻辑）
          localStorage.setItem('token', 'user_session')
          // 跳转到首页
          router.push('/dashboard')
        } else {
          console.log('用户登录失败 - 原因:', response.data?.msg)
          ElMessage.error(response.data?.msg || '登录失败')
        }
      }
    } else {
      console.log('响应代码不是200:', response.code, response.msg)
      ElMessage.error(response.msg || '登录失败')
    }
  } catch (error) {
    ElMessage.error('登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 40px;
  animation: slideUp 0.6s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.login-header p {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.login-form {
  margin-bottom: 20px;
}

.user-type-group {
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.login-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  transition: all 0.3s ease;
}

.login-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.login-footer {
  text-align: center;
  margin-top: 20px;
}

.login-footer p {
  color: #999;
  font-size: 12px;
  margin: 0;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
}

:deep(.el-radio) {
  margin-right: 0;
}

:deep(.el-radio__label) {
  font-weight: 500;
  color: #333;
}
</style>


